package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcDemo {

	public static void main(String[] args) {

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			// 1、加载数据库驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2、创建并获取数据库连接
			connection = DriverManager
					.getConnection(
							"jdbc:mysql:///mybatis?characterEncoding=utf-8",
							"root", "1234");
			// 4、编写SQL语句
			String sql = "select * from user where username = ?";
			// 3、创建jdbc statement对象
			preparedStatement = connection.prepareStatement(sql);
			// 5、设置sql语句中的参数
			preparedStatement.setString(1, "张三丰");
			// 6、通过statement执行sql并获取结果
			resultSet = preparedStatement.executeQuery();
			// 7、对sql语句执行结果进行解析处理
			while (resultSet.next()) {
				System.out.println(resultSet.getString("id") + " "
						+ resultSet.getString("username"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 8、释放资源
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
